<?php

namespace app\admin\controller;

use app\admin\model\AdminUser;
use app\admin\validate\LoginValidate;
use app\BaseController;
use Firebase\JWT\JWT;
use think\facade\Request;

class Login  extends BaseController
{
    public function managerLogin() {
        $params = $this->request->post(['username', 'password']);
        $validate = new LoginValidate();
        if (!$validate->scene('login')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new AdminUser();
        $info = $sql->where([
            ["username", '=', $params['username']],
            ["password", '=', $params['password']],
        ])->find();

        if(empty($info)) {
            return  result()->fail("账号或密码不正确", 500);
        }
        $payload = array(
            "iat" => time(), // 签发时间
            "ext" => strtotime("7 day"), // 过期时间
            "data"=> [
                'id' => "ADMIN:".$info->id,
                'password' => $info->password
            ]
        );
        $info->token = JWT::encode($payload, config('app.jwt.secret'), config('app.jwt.algo'));
        $info->save();
        return result()->success(['token' => $info['token']]);
    }
}